package com.codechen.scaffold.books.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codechen.scaffold.books.domain.entity.Book;
import com.codechen.scaffold.books.domain.req.BookQueryRequest;
import com.codechen.scaffold.books.domain.req.BookSaveRequest;
import com.codechen.scaffold.books.service.IBookService;
import com.codechen.scaffold.common.domain.Result;
import com.codechen.scaffold.common.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author : wuweihong
 * @desc : TODO  请填写你的功能描述
 * @date : 2025-06-19
 */

@RestController
@RequestMapping("/book")
@Api(tags = "书籍管理")
public class BookController {

	@Autowired
	private IBookService bookService;

	@ApiOperation(value = "书籍列表")
	@PostMapping("/pageList/{pageNo}/{pageSize}")
	public Result list(@PathVariable(value = "pageNo") Long pageNo,
	                   @PathVariable(value = "pageSize") Long pageSize,
	                   @RequestBody BookQueryRequest bookQueryRequest) {
		Page<Book> page = new Page<>(pageNo, pageSize);
		IPage<Book> newsBaseVOIPage = bookService.queryList(page, bookQueryRequest);
		return Result.success(newsBaseVOIPage);
	}

	@ApiOperation(value = "保存书籍")
	@PostMapping("/save")
	public Result<Void> save(@RequestBody BookSaveRequest bookSaveRequest) {
		Book book = new Book();
		BeanUtils.copyProperties(bookSaveRequest, book);
		bookService.save(book);
		return Result.success(null);
	}

	@ApiOperation(value = "删除")
	@GetMapping("/del/{id}")
	public Result<Void> del(@PathVariable("id") Long id) {
		Book book = bookService.getById(id);
		if (Objects.nonNull(book)) {
			if (book.getBorrownum() > 0) {
				throw new BusinessException(500, "图书已被借阅，不可删除");
			}
			bookService.removeById(book);
		}
		return Result.success(null);
	}

}
